<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
use Laravel\Passport\Events\AccessTokenCreated;
use Laravel\Passport\Token;

class RevokeAccessTokens implements ShouldQueue {
	protected $token;

	/**
	 * Create the event listener.
	 *
	 * @return void
	 */
	public function __construct(Token $token) {
		$this->token = $token;
	}

	/**
	 * Handle the event.
	 *
	 * @param  object  $event
	 * @return void
	 */
	public function handle(AccessTokenCreated $event) {
		$refresh_tokens = $this->token->where('user_id', $event->userId)->select('id')->orderBy('created_at', 'asc')->get();
		if ($refresh_tokens) {
			$access_tokens = array_column($refresh_tokens->toArray(), 'id');
			array_pop($access_tokens);
			DB::table('oauth_refresh_tokens')->whereIn('access_token_id', $access_tokens)->delete();
		}
		$this->token->where('user_id', $event->userId)->where('client_id', $event->clientId)->where('id', '<>', $event->tokenId)->delete();
	}
}
